package com.google.appengine.a4ieve.servlets.resources;

import com.google.appengine.a4ieve.Const;
import com.google.appengine.a4ieve.Helper;
import com.google.appengine.a4ieve.entities.StudentWrapper;
import com.google.appengine.api.datastore.*;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * User: lunin
 * Date: 4/24/14
 * Time: 8:58 AM
 */
public class GetStudentsServant implements Servant {

    private static final Logger LOG = Logger.getLogger(GetCuratorServant.class.getName());

    @Override
    public void process(HttpServletRequest req, HttpServletResponse resp) {
        DatastoreService store = DatastoreServiceFactory.getDatastoreService();
        JSONObject requestJson = (JSONObject) req.getAttribute(Const.INNER_JSON);
        int page = 0;
        int count = 0;
        if (requestJson.has(Const.PAGE) && requestJson.has(Const.COUNT)) {
            page = Integer.parseInt((String) requestJson.get(Const.PAGE));
            count = Integer.parseInt((String) requestJson.get(Const.COUNT));
        }
        List<Entity> studentEntities = new LinkedList<Entity>();
        String groupId = (String) req.getSession().getAttribute(Const.GROUP);
        LOG.severe("Group id for filtering " + groupId);
        Query studentQuery = new Query(StudentWrapper.KIND_KEY).addFilter(
                StudentWrapper.GROUP_KEY_PROPERTY,
                Query.FilterOperator.EQUAL,
                groupId)
                .addSort(StudentWrapper.STUDENT_NAME_PROPERTY).setKeysOnly();
        FetchOptions options = FetchOptions.Builder.withDefaults();
        if (page != 0 && count != 0) {
            options = FetchOptions.Builder.withOffset((page - 1) * count).limit(count);
        }
        studentEntities = store.prepare(studentQuery).asList(options);
        Query totalCountQuery = new Query(StudentWrapper.KIND_KEY).addFilter(
                StudentWrapper.GROUP_KEY_PROPERTY,
                Query.FilterOperator.EQUAL,
                groupId);
        int total = store.prepare(totalCountQuery).countEntities(FetchOptions.Builder.withDefaults());
        try {
            LOG.severe("Present student entities: " + studentEntities);
            Helper.writeEntitiesToJson(StudentWrapper.class, studentEntities, total, store).write(resp.getWriter());
        } catch (IOException i) {
            LOG.severe("Error while writing curator information " + i);
        }
    }
}
